package dingding

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	"gitee.com/lcc_dr/webhook.git/conf"
	"github.com/julienschmidt/httprouter"
)

var URL string

const ContentType string = "application/json"

func sendmsgd(r *http.Request) error {

	lenr := r.ContentLength
	buff := make([]byte, lenr)
	r.Body.Read(buff)
	defer r.Body.Close()

	log.Printf("打印prometheus alert 原始数据…%s", (string(buff[:])))
	//fmt.Println(string(buff[:]))

	var msg conf.ResMsg
	log.Printf("unmarshal 为json")
	json.Unmarshal(buff, &msg)

	status := msg.Status
	if len(msg.Alerts) > 0 {
		description := msg.Alerts[0].Annotations["description"]
		startsAt := (msg.Alerts[0].StartsAt).Format("2006-01-02 15:04:05")
		alert_msg := fmt.Sprintf("[das_alert %s] 时间: %s ,告警内容%s \n", status, startsAt, description)

		sendmsgjson := conf.GetDefaultSendMsg()
		sendmsgjson.Msgtype = conf.GetConf().Msgtype
		sendmsgjson.Text["content"] = alert_msg
		sendmsgjson.At = conf.GetConf().At

		URL := conf.GetConf().URL

		msgs_json, err := json.Marshal(sendmsgjson)
		if err != nil {
			panic(err)
		}
		log.Println(string(msgs_json))

		msga_body := bytes.NewBuffer([]byte(msgs_json))
		//发送post 请求

		fmt.Println(&URL)
		resp, err := http.Post(URL, ContentType, msga_body)
		if err != nil {

			log.Println(err)

		}

		body, err := ioutil.ReadAll(resp.Body)
		defer resp.Body.Close()
		/*
			lenr := r.ContentLength
			buff := make([]byte, lenr)
			r.Body.Read(buff)
			defer resp.Body.Close()
			fmt.Println(string(buff))
		*/

		//var di (map[string]interface{})
		var di conf.DingResponse
		err = json.Unmarshal(body, &di)
		if err != nil {
			log.Printf(" 发送请求返回解析失败")
		}

		log.Printf(" 返回状态码是： %d \n", di.Errcode)
		log.Printf(" 返回信息是： %s \n", di.Errmsg)

	} else {

		return fmt.Errorf("alert msg is empty")
	}
	return nil

}

func Index(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {

	sendmsgd(r)

}

func Hello(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
	fmt.Fprintf(w, "hello, %s!\n", ps.ByName("name"))
}

func DingDingWebhook(listenaddr string) {

	router := httprouter.New()

	router.POST("/", Index)
	log.Println("webhook start is successful")
	err := http.ListenAndServe(listenaddr, router)
	if err != nil {
		log.Fatal(err)
	}

}

/*
func init() {
	err := conf.LoadConfigFromToml("../../etc/ding_text.toml")
	if err != nil {
		panic(err)
	}

}
*/
